package com.dfs.parent.common.feign.openfeign;

import com.dfs.parent.common.core.constant.GrayConstant;
import com.dfs.parent.common.feign.context.GrayContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description TODO
 * @Author dahong
 * @Date 2024/2/22 22:52
 */
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        // 如果灰度标记为true，将灰度标记通过HttpHeader传递下去
        if (GrayConstant.GRAY_HEADER_TAG_VALUE_TRUE.equals(GrayContextHolder.getGrayTag())) {
            template.header(GrayConstant.GRAY_HEADER_TAG, GrayConstant.GRAY_TAG_VALUE_TRUE);
        }
//        String traceId = TraceContext.getCorrelation("traceId").get();
//        if (StrUtil.isEmpty(traceId)) {
//
//            traceId = TraceContext.traceId();
//            TraceContext.putCorrelation("traceId", traceId);
//            template.header("traceId", traceId);
//
//        }
        Optional<String> optional = TraceContext.getCorrelation("traceId"); // 这是你的Optional对象
        if (optional.isPresent()) {
            //String value = optional.get();
            // 使用value
           // TraceContext.putCorrelation("traceId", optional.get());
            log.info("=====traceId = {} ", optional.get());
            template.header("traceId", optional.get());
        } else {
            // 处理Optional为空的情况
            log.info("======TraceContext.traceId()1=====>{}",TraceContext.traceId());
            TraceContext.putCorrelation("traceId", TraceContext.traceId());
            template.header("traceId",  TraceContext.traceId());
            log.info("======TraceContext.traceId()2=====>{}",TraceContext.traceId());
        }
//        TraceContext.putCorrelation("traceId", traceId);
//        Optional<String> op = TraceContext.getCorrelation("myKey");
//        log.info("myValue = {} ", op.get());

            ServletRequestAttributes attributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (null != attributes) {
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();

//                if (null != headerNames) {
//                    while (headerNames.hasMoreElements()) {
//                        String name = headerNames.nextElement();
//                        String values = request.getHeader(name);
//                        if(name.equals(TokenConstant.DFS_TOKEN)){
//                            template.header(name, values);
//                           // template.header(TokenConstant.DFS_TOKEN, values);
//                        }
//                        /** 不能把当前请求的 content-length 传递到下游的服务提供方, 这明显是不对的
//                         * 请求可能一直返回不了, 或者是请求响应数据被截断
//                         */
//
////                        if (!name.equalsIgnoreCase("content-length")) {
////                            // 这里的 template 就是 RestTemplate
//                        //    template.header(name, values);
////                        }
//                    }
//                }

                try {
                    // 1. 安全获取请求头
                    Map<String, Collection<String>> headers = Optional.ofNullable(template.headers())
                            .orElse(Collections.emptyMap());

                    // 2. 处理特定header
                    headers.forEach((key, values) -> {
                        if (key != null && values != null) {
                            values.stream()
                                    .filter(Objects::nonNull)
                                    .forEach(value -> template.header(key, value));
                        }
                    });

                    // 3. 添加新header时的空检查
//                    String authHeader = getAuthHeaderSafely();
//                    if (authHeader != null) {
//                        template.header("Authorization", authHeader);
//                    }
//                    private String getAuthHeaderSafely() {
//                        // 实现安全的header获取逻辑
//                    }

                } catch (Exception e) {
                    log.error("Feign拦截器处理请求头失败", e);
                    throw e;
                }
            }



    }
}
